package com.atguigu.chapter09;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternSelectFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.PatternTimeoutFunction;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.List;
import java.util.Map;

/**
 * Author: Pepsi
 * Date: 2023/8/22
 * Desc:
 */
public class Flink08_CEP_WithIn {
    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);


        // 1. 定义一个流
        SingleOutputStreamOperator<WaterSensor> stream = env
                .readTextFile("input/sensor.txt")
                .map(line -> {
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((ws, ts) -> ws.getTs())
                );

        // 2. 定义一个模式
        Pattern<WaterSensor, WaterSensor> pattern = Pattern

                .<WaterSensor>begin("s1")
                .where(new SimpleCondition<WaterSensor>() {
                    @Override
                    public boolean filter(WaterSensor value) throws Exception {
                        return "sensor_1".equals(value.getId());
                    }
                })
                .next("s2")
                .where(new SimpleCondition<WaterSensor>() {
                    @Override
                    public boolean filter(WaterSensor value) throws Exception {
                        return "sensor_2".equals(value.getId());
                    }
                })
                // 这个是限制前面两个数据的时间间隔在2s以内，不包含2s，必须在2s内
                .within(Time.seconds(2));


        // 3. 用CEP类，将模式应用到流中，得到模式流
        PatternStream<WaterSensor> ps = CEP.pattern(stream, pattern);

        // 4. 从模式流中选择数据
        // 迟到的数据可以从侧输出流中取出来
        SingleOutputStreamOperator<String> normal = ps.select(
                // 注意用侧输出流，一定要记得加{} 存在泛型擦除，不能自动推断出类型
                new OutputTag<WaterSensor>("late"){},
                new PatternTimeoutFunction<WaterSensor, WaterSensor>() {
                    @Override
                    public WaterSensor timeout(Map<String, List<WaterSensor>> pattern, long timeoutTimestamp) throws Exception {
                        return pattern.get("s1").get(0);
                    }
                },
                new PatternSelectFunction<WaterSensor, String>() {
                    @Override
                    public String select(Map<String, List<WaterSensor>> pattern) throws Exception {
                        return pattern.toString();
                    }
                }
        );

        normal.print("normal");
        normal.getSideOutput(new OutputTag<WaterSensor>("late"){}).print("timeOut");

        // 如果时间超过2s没有数据来叫不匹配，如果时间走过了2s来了数据但不是sensor_2这个叫超时数据（迟到）

        /*
        * 1. 匹配成功的数据   可以拿到
        *
        * 2. 超时迟到的数据    侧输出流里面可以拿到
        *
        * 3. 匹配不上的数据    直接丢弃
        *
        * */

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
